package br.com.rapidrest.demo.service;

import java.util.Properties;

import javax.naming.InitialContext;
import javax.transaction.TransactionManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.Before;
import org.mycontainer.datasource.DataSourceDeployer;
import org.mycontainer.ejb.SessionInterceptorDeployer;
import org.mycontainer.ejb.StatelessScannableDeployer;
import org.mycontainer.jpa.JPADeployer;
import org.mycontainer.jpa.JPAInfoBuilder;
import org.mycontainer.kernel.ShutdownCommand;
import org.mycontainer.kernel.boot.ContainerBuilder;
import org.mycontainer.kernel.deploy.ScannerDeployer;

import br.com.rapidrest.demo.domain.PhoneBook;

public abstract class AbstractTestCase {

	private static final Log LOG = LogFactory.getLog(AbstractTestCase.class);

	protected ContainerBuilder builder;

	protected TransactionManager tm;

	private InitialContext ctx;

	@Before
	public void boot() throws Exception {
		builder = new ContainerBuilder();

		SessionInterceptorDeployer sessionInterceptorDeployer = builder
				.createDeployer(SessionInterceptorDeployer.class);
		sessionInterceptorDeployer.deploy();

		builder.deployJTA();

		DataSourceDeployer ds = builder
				.createDeployer(DataSourceDeployer.class);
		ds.setName("DemoDS");
		ds.setDriver("org.hsqldb.jdbcDriver");
		ds.setUrl("jdbc:hsqldb:mem:.");
		ds.setUser("sa");
		ds.deploy();

		JPADeployer jpa = builder.createDeployer(JPADeployer.class);
		JPAInfoBuilder info = (JPAInfoBuilder) jpa.getInfo();
		info.setPersistenceUnitName("demo-pu");
		info.setJtaDataSourceName("DemoDS");
		info.addJarFileUrl(PhoneBook.class);
		info.setPersistenceUnitRootUrl(PhoneBook.class);
		Properties props = info.getProperties();
		props.setProperty("hibernate.dialect",
				"org.hibernate.dialect.HSQLDialect");
		props.setProperty("hibernate.hbm2ddl.auto", "create-drop");
		props.setProperty("hibernate.show_sql", "true");
		jpa.deploy();

		ScannerDeployer scanner = builder.createDeployer(ScannerDeployer.class);
		scanner.add(new StatelessScannableDeployer());
		scanner.scan(PhoneBookServiceBean.class);
		scanner.deploy();

		ctx = builder.getContext();
		tm = (TransactionManager) ctx.lookup("TransactionManager");

	}

	@After
	public void shutdown() {
		try {
			ShutdownCommand shutdown = new ShutdownCommand();
			shutdown.setContext(new InitialContext());
			shutdown.shutdown();
		} catch (Exception e) {
			LOG.error("Error shutdown", e);
		}
	}
}
